<!--  -->
<template>
  <div class="customer-service f-18" ref="container">
    <Nav :selfCenter="true">
      <template v-slot:center>
        <div class="title-center 'f-14'">
          {{title}}
          <span
            :class="[{'color-green':online==1},{'color-gray':online==-1}]"
          >{{online==1?'在线':online==-1?'离线':''}}</span>
        </div>
      </template>
      <template v-slot:left>
        <span class="back" @click="$router.back()"></span>
      </template>
    </Nav>
    <!-- scroll -->
    <div class="srcoll-wrapper" ref="srcollWrapper">
      <Scroll
        :preventDefault="true"
        :click="true"
        :tap="true"
        :pullup="true"
        :pulldown="true"
        :listenScroll="true"
        @pulldown="pulldown"
        :data.sync="chatList"
        ref="myScroll"
      >
        <ChatList :chatList.sync="chatList"></ChatList>
      </Scroll>
    </div>
    <emotion v-if="emotionFlag" class="emotion" @emotion="handleEmotion" :height="200"></emotion>
    <div class="bottom-bar">
      <div class="icon-list">
        <span class="icon-item smail" @click="emotionFlag=!emotionFlag"></span>
        <van-uploader :after-read="afterReadPic" multiple>
          <span class="icon-item pic"></span>
        </van-uploader>
        <!-- <van-uploader accept="file" :after-read="afterReadFile">
          <span class="icon-item file"></span>
        </van-uploader>-->
      </div>
      <div class="send-wrapper flex">
        <input class="input f-14" type="text" v-model="input" @blur="inputBlur">
        <button class="btn flex justify-center aligin-center color-white f-14" @click="sendMsg">发送</button>
      </div>
    </div>
  </div>
</template>

<script>
import Scroll from "../../components/Scroll";
import Nav from "../../components/Nav";
import ChatList from "../../components/ChatList";
import Page from "../../mixin/page";
import Emotion from "../../components/Emotion/index";
import axios from "axios";
import config from "../../utils/config";
import compress from "../../utils/picCompress";
export default {
  mixins: [Page],
  components: { Scroll, Nav, ChatList, Emotion },
  data() {
    return {
      input: "",
      chat_id: "",
      title: "客服A",
      chatList: [],
      emotionFlag: false,
      oldScrollHeight: 0,
      timer: null,
      reconnectTimer: null,
      current_page: 0,
      last_page: 1,
      online: -1,
      bfscrolltop: 0
    };
  },
  computed: {
    noMore() {
      return this.last_page == this.current_page;
    }
  },
  watch: {
    chatList(newValue, oldValue) {
      if (this.$refs.myScroll.scroll) {
        setTimeout(() => {
          this.$refs.myScroll.scroll.scrollBy(
            0,
            this.oldScrollHeight - this.$refs.myScroll.scroll.scrollerHeight,
            100
          );
          this.oldScrollHeight = this.$refs.myScroll.scroll.scrollerHeight;
        }, 100);
      }
    }
  },
  methods: {
    inputBlur() {
      // this.$refs.container.style.paddingBottom=0+'px'
      document.body.scrollTop = this.bfscrolltop;
    },
    //上拉
    pulldown() {
      if (this.noMore) {
        return;
      }
      this._socketSend();
    },
    onMessage(event) {
      let res = JSON.parse(event.data);
      if (
        res.channel == "message" &&
        res.data.list &&
        typeof res.data == "object"
      ) {
        this.chat_id = res.data.chat_id;
        this.title = res.data.shop_name;
        this.online = res.data.online;
        let _list = res.data.list.map(item => {
          if (item.type == 2) {
            return item;
          }
          let array = item.content.split("[#");
          let content = [];
          if (array.length == 1 && !array[0].match("]")) {
            content.push({
              textContent: array[0],
              type: "text"
            });
          } else {
            for (let i = 0; i < array.length; i++) {
              if (parseInt(array[i]) >= 0 && array[i].match("]")) {
                let _array = array[i].split("]");
                for (let i = 0; i < _array.length; i++) {
                  if (parseInt(_array[i]) >= 0 && i == 0) {
                    content.push({
                      textContent: _array[i],
                      type: "img"
                    });
                  } else {
                    content.push({
                      textContent: _array[i],
                      type: "text"
                    });
                  }
                }
              } else {
                content.push({
                  textContent: array[i],
                  type: "text"
                });
              }
            }
          }

          item.content = content;
          return item;
        });
        if (_list && _list.length != 0) {
          this.current_page += 1;
          this.last_page = this.current_page + 1;
        } else {
          this.last_page = this.current_page;
        }
        this.chatList = [..._list, ...this.chatList];
      } else if (
        (res.channel == "send" || res.channel == "u_send") &&
        res.data
      ) {
        if (res.data.type == 2) {
        } else {
          let array = res.data.content.split("[#");
          let content = [];
          if (array.length == 1 && !array[0].match("]")) {
            content.push({
              textContent: array[0],
              type: "text"
            });
          } else {
            for (let i = 0; i < array.length; i++) {
              if (parseInt(array[i]) >= 0 && array[i].match("]")) {
                let _array = array[i].split("]");
                for (let i = 0; i < _array.length; i++) {
                  if (parseInt(_array[i]) >= 0 && i == 0) {
                    content.push({
                      textContent: _array[i],
                      type: "img"
                    });
                  } else {
                    content.push({
                      textContent: _array[i],
                      type: "text"
                    });
                  }
                }
              } else {
                content.push({
                  textContent: array[i],
                  type: "text"
                });
              }
            }
          }

          res.data.content = content;
        }
        // console.log(content);
        this.chatList.push(res.data);
      }
    },
    handleEmotion(i) {
      let word = i.replace(/\#|\;/gi, "");
      const list = [
        "微笑",
        "撇嘴",
        "色",
        "发呆",
        "得意",
        "流泪",
        "害羞",
        "闭嘴",
        "睡",
        "大哭",
        "尴尬",
        "发怒",
        "调皮",
        "呲牙",
        "惊讶",
        "难过",
        "酷",
        "冷汗",
        "抓狂",
        "吐",
        "偷笑",
        "可爱",
        "白眼",
        "傲慢",
        "饥饿",
        "困",
        "惊恐",
        "流汗",
        "憨笑",
        "大兵",
        "奋斗",
        "咒骂",
        "疑问",
        "嘘",
        "晕",
        "折磨",
        "衰",
        "骷髅",
        "敲打",
        "再见",
        "擦汗",
        "抠鼻",
        "鼓掌",
        "糗大了",
        "坏笑",
        "左哼哼",
        "右哼哼",
        "哈欠",
        "鄙视",
        "委屈",
        "快哭了",
        "阴险",
        "亲亲",
        "吓",
        "可怜",
        "菜刀",
        "西瓜",
        "啤酒",
        "篮球",
        "乒乓",
        "咖啡",
        "饭",
        "猪头",
        "玫瑰",
        "凋谢",
        "示爱",
        "爱心",
        "心碎",
        "蛋糕",
        "闪电",
        "炸弹",
        "刀",
        "足球",
        "瓢虫",
        "便便",
        "月亮",
        "太阳",
        "礼物",
        "拥抱",
        "强",
        "弱",
        "握手",
        "胜利",
        "抱拳",
        "勾引",
        "拳头",
        "差劲",
        "爱你",
        "NO",
        "OK",
        "爱情",
        "飞吻",
        "跳跳",
        "发抖",
        "怄火",
        "转圈",
        "磕头",
        "回头",
        "跳绳",
        "挥手",
        "激动",
        "街舞",
        "献吻",
        "左太极",
        "右太极"
      ];
      let index = list.indexOf(word);
      this.input += `[#${index}]`;
      this.emotionFlag = false;
    },
    sendMsg() {
      if (this.input) {
        let param = JSON.stringify({
          channel: "send",
          data: {
            token: this.$store.state.token,
            content: {
              shop_id: this.$route.query.shop_id,
              message: this.input,
              type: 1,
              chat_id: this.chat_id
            }
          }
        });

        window.socket.send(param);
        this.input = "";
      }
    },
    initWS() {
      window.socket.onclose = () => {
        // reset
        this.chatList = [];
        this.current_page = 0;
        this.last_page = 1;
        clearInterval(this.reconnectTimer);
        this.reconnectTimer = null;
        this.reconnectTimer = setInterval(() => {
          if (window.socket.readyState == 1) {
            this.initWS();
            this._socketSend();
            clearInterval(this.reconnectTimer);
            this.reconnectTimer = null;
          }
        }, 2000);
      };
      window.socket.onerror = () => {
        // reset
        this.chatList = [];
        this.current_page = 0;
        this.last_page = 1;
        clearInterval(this.reconnectTimer);
        this.reconnectTimer = null;
        this.reconnectTimer = setInterval(() => {
          if (window.socket.readyState == 1) {
            this.initWS();
            this._socketSend();
            clearInterval(this.reconnectTimer);
            this.reconnectTimer = null;
          }
        }, 2000);
      };
      window.socket.onmessage = event => {
        this.onMessage(event);
      };
    },
    _socketSend() {
      let param = JSON.stringify({
        channel: "message",
        data: {
          token: this.$store.state.token,
          content: {
            shop_id: this.$route.query.shop_id,
            id: this.$route.query.id,
            page: this.current_page + 1
          }
        }
      });
      window.socket.send(param);
    },

    afterReadPic(file) {
      compress(file)
        .then(_file => {
          console.log("file", _file);
          let formData = new FormData();
          formData.append("img", _file);
          return axios.post(config.baseUrl + "/api/image/upload", formData, {
            headers: {
              authorization: "bearer " + this.$store.state.token
            }
          });
        })
        .then(({ data: { result } }) => {
          let param = JSON.stringify({
            channel: "send",
            data: {
              token: this.$store.state.token,
              content: {
                shop_id: this.$route.query.shop_id,
                message: result.url,
                type: 2,
                chat_id: this.chat_id
              }
            }
          });
          window.socket.send(param);
        })
        .catch(err => {});
    }
  },
  created() {},
  mounted() {
    setTimeout(() => {
      this.oldScrollHeight = this.$refs.myScroll.scroll.scrollerHeight;
      this.$refs.myScroll.scroll.scrollTo(
        0,
        -this.$refs.myScroll.scroll.scrollerHeight +
          this.$refs.srcollWrapper.offsetHeight,
        0
      );
    }, 100);
    this.bfscrolltop = document.body.scrollTop;
    //websocket
    this.initWS();
    if (window.socket.readyState == 1) {
      let param = JSON.stringify({
        channel: "auth",
        data: { token: this.$store.state.token, content: "auth" }
      });
      window.socket.send(param);
      this._socketSend();
    } else {
      this.timer = setInterval(() => {
        if (window.socket.readyState == 1) {
          this._socketSend();
          clearInterval(this.timer);
          this.timer = null;
        }
      }, 1000);
    }
  },
  updated() {}, //生命周期 - 更新之后
  destroyed() {
    clearInterval(this.timer);
    this.timer = null;
    clearInterval(this.reconnectTimer);
    this.reconnectTimer = null;
  } //生命周期 - 销毁完成
};
</script>
<style lang='less' scoped>
@import url("../../assets/style/mixin"); //引入公共css类
.customer-service {
  height: 100%;
}
.color-green {
  color: green;
}
.title-center {
  text-align: center;
}
.srcoll-wrapper {
  height: calc(100% - 132px);
  overflow: hidden;
}
.emotion {
  position: fixed;
  bottom: 87px;
  left: 0;
  width: 100%;
  background: #fff;
}
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 87px;
  .icon-list {
    height: 37px;
    .icon-item {
      display: inline-block;
      margin: 6px;
      height: 25px;
      width: 25px;
    }
    .smail {
      background: url("../../assets/imgs/smail.png");
      background-size: 100% 100%;
    }
    .pic {
      background: url("../../assets/imgs/pic.png");
      background-size: 100% 100%;
    }
    .file {
      background: url("../../assets/imgs/file.png");
      background-size: 100% 100%;
    }
  }
  .send-wrapper {
    margin: 0 6px;
    height: 38px;
  }
  .input {
    text-indent: 10px;
    flex: 1;
    height: 100%;
    // line-height: 40px;
    border: 1px solid #ebebeb;
  }
  .btn {
    width: 65px;
    height: 38px;
    .bg-1();
  }
}
</style>